import moment from 'moment';
import { axios } from '@/api/api';
import config from '@/config/app.config';

export function savePageActivityRecord({pageKey, eventType}) {
  if (config.get('isDeveloperMachine') || ['localhost', '127.0.0.1'].includes(location.hostname) || location.hostname.startsWith('192.168')) {
    return;
  }
  const now = moment().format('YYYY-MM-DD HH:mm:ss');

  // 依赖于格式 pageKey = <pagePath>__<extraKey>，而<pagePath>不包含'_'字符
  let pagePath, extraPageKey;
  let keyIndex = pageKey.indexOf('__');
  if (keyIndex > -1) {
    pagePath = pageKey.substring(0, keyIndex);
    extraPageKey = pageKey.substring(keyIndex + 2);
  } else {
    pagePath = pageKey;
    extraPageKey = undefined;
  }

  setTimeout(() => {
    axios.post('/api/sys/page_activity_record', {
      pagePath,
      extraPageKey,
      eventTime: now,
      eventType: {created: 1, resumed: 2, removed: 3}[eventType]
    });
  }, 0);
}